package com.ciwong.epaper.modules.epaper.dao;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.dbbean.AnswerContent;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.dbbean.LswProgress;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.LswCommitAnswer;
import com.ciwong.epaper.modules.epaper.bean.LswSubCommitAnswer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/2/16.
 * 听说模考专用
 */
public class LswDao {

    private static LswDao instance;
    private Handler mHandler;

    public LswDao() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * 获取唯一实例
     *
     * @return 唯一实例
     */
    public static LswDao getInstance() {
        if (instance == null) {
            syncInit();
        }
        return instance;
    }

    /**
     * 实例化对象
     */
    private static synchronized void syncInit() {
        if (instance == null) {
            instance = new LswDao();
        }
    }

    /**
     * 提交mp3 碎片打分
     */
    public void submitMakeScore(LswAnswer lswAnswer, boolean isCorrect, final BaseCallBack callBack) {

        LswRequest.submitMakeScore(lswAnswer, isCorrect, callBack);

    }

    /**
     * 设置做作业进度
     */
    public void onUploadDoworkProgress(final LswProgress lswProgress, final BaseCallBack callBack) {

        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                String json = new Gson().toJson(lswProgress, LswProgress.class);
                try {
                    LswRequest.onUploadDoworkProgress(json, callBack);
                } catch (Exception e) {
                    if (e != null) {
                        Log.d("onUploadDoworkProgress", "############e#############" + e.getMessage());
                    }
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.failed(R.string.unknown_error);
                        }
                    });
                    return;
                }


            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

    }

    /**
     * 提交作业或者练习
     */
    public void submitHomeWork(final String uuid, final String workId, final String classId, final int totalTime, final int serviceId,
                               final List<LswAnswer> userAnswersList,
                               final DownLoadInfo downLoadInfo, final Module module,
                               final int position, final int contentId, final float workScore, final int audioAnswerSize, final String errorWorkId, final int doWorkType, final long startTime, final BaseCallBack callBack) {

        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();

                LswCommitAnswer lswCommitAnswer = new LswCommitAnswer();
                lswCommitAnswer.setStartTime(startTime);
                lswCommitAnswer.setSessionId(uuid);
                lswCommitAnswer.setWorkId(workId);
                lswCommitAnswer.setAudioAnswerSize(audioAnswerSize);
                if (errorWorkId != null) {
                    if (doWorkType == 1) {
                        lswCommitAnswer.setErrorWorkId(errorWorkId);
                    } else if (doWorkType == 2) {
                        lswCommitAnswer.setDoWorkId(errorWorkId);
                    }
                }
                if (null != classId) {
                    lswCommitAnswer.setClassId(Integer.valueOf(classId));
                }
                lswCommitAnswer.setPackageId(downLoadInfo.getBookId());
                lswCommitAnswer.setcId(downLoadInfo.getChapterId());
                lswCommitAnswer.setWorkLong(totalTime);
                //服务id
                if (serviceId > 0) {
                    lswCommitAnswer.setWorkType(serviceId);
                }

                lswCommitAnswer.setBrandId(EApplication.BRAND_ID);
                if (null != EApplication.getInstance().getUserInfoBase()) {
                    lswCommitAnswer.setUserName(EApplication.getInstance().getUserInfoBase().getRealName());
                }

                lswCommitAnswer.setContentId(contentId);
                lswCommitAnswer.setWorkScore(workScore);

                int moduleId;


                if (downLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {

                    lswCommitAnswer.setModuleId(Integer.valueOf(downLoadInfo.getModuleId()));
                    lswCommitAnswer.setVersionId(downLoadInfo.getVersionId());
                    lswCommitAnswer.setParentVersionId("0");

                    if (TextUtils.isEmpty(downLoadInfo.getResourceName())) {
                        lswCommitAnswer.setResourceName("  ");
                    } else {
                        lswCommitAnswer.setResourceName(downLoadInfo.getResourceName());
                    }

                    if (TextUtils.isEmpty(downLoadInfo.getResourceName())) {
                        lswCommitAnswer.setResourceType("  ");
                    } else {
                        lswCommitAnswer.setResourceType(downLoadInfo.getResourceType());
                    }

                } else if (module != null) {
                    ModuleContent moduleContent = module.getResourceList().get(position);
                    moduleId = module.getModuleInfo().getModuleId();
                    lswCommitAnswer.setModuleId(moduleId);
                    lswCommitAnswer.setVersionId(moduleContent.getVersionId());
                    lswCommitAnswer.setParentVersionId(moduleContent.getParentVersionId());

                    if (TextUtils.isEmpty(moduleContent.getResourceName())) {
                        lswCommitAnswer.setResourceName("");
                    } else {
                        lswCommitAnswer.setResourceName(moduleContent.getResourceName());
                    }

                    if (TextUtils.isEmpty(moduleContent.getResourceType())) {
                        lswCommitAnswer.setResourceType("");
                    } else {
                        lswCommitAnswer.setResourceType(moduleContent.getResourceType());
                    }

                }

                List<LswSubCommitAnswer> lswSubCommitAnswerList = new ArrayList<LswSubCommitAnswer>();


                //选择填空才需要
                if (null != userAnswersList && userAnswersList.size() > 0) {
                    for (LswAnswer lswAnswer : userAnswersList) {

                        LswSubCommitAnswer lswSubCommitAnswer = new LswSubCommitAnswer();
                        lswSubCommitAnswer.setVersionId(lswAnswer.getVersionId());
                        lswSubCommitAnswer.setRefScore(lswAnswer.getRefScore());
                        lswSubCommitAnswer.setBigQuesIndex(lswAnswer.getBigQuesIndex());
                        lswSubCommitAnswer.setTotalQuesIndex(lswAnswer.getTotalQuesIndex());
                        lswSubCommitAnswer.setQuesNo(lswAnswer.getQuesNo());

                        lswSubCommitAnswer.setAnswerType(lswAnswer.getAnswerType());

                        if (null != lswAnswer.getAnswerContents()) {
                            lswSubCommitAnswer.setAnswer(lswAnswer.getAnswerContents());
                        }
                        lswSubCommitAnswerList.add(lswSubCommitAnswer);
                    }


                    String userAnswerJson = gson.toJson(lswSubCommitAnswerList, new TypeToken<List<LswSubCommitAnswer>>() {
                    }.getType());
                    if (!TextUtils.isEmpty(userAnswerJson)) {
                        lswCommitAnswer.setTextWorkAnswers(userAnswerJson);
                    } else {
                        lswCommitAnswer.setTextWorkAnswers("[]");
                    }

                } else {
                    //空json
                    lswCommitAnswer.setTextWorkAnswers("[]");
                }

                String json = new Gson().toJson(lswCommitAnswer, LswCommitAnswer.class);

                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String key = "textWorkAnswers";
                    if (jsonObject.has(key)) {
                        JSONArray array = new JSONArray(lswCommitAnswer.getTextWorkAnswers());
                        jsonObject.remove(key);
                        jsonObject.put(key, array);
                        json = jsonObject.toString();
                    }

                    LswRequest.submitHomeWork(json, doWorkType, callBack);

                } catch (Exception e) {

                    if (e != null) {
                        Log.d("retryscore", "############e#############" + e.getMessage());
                    }
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.failed(R.string.read_answer_file_error);
                        }
                    });
                    return;
                }


            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

    }


    /**
     * 获取听说模考作业或自主练习评分
     *
     * @param doworkId 提交作业或练习返回的doworkId, 不是workId
     */
    public void getLswScoreResult(String doworkId, final BaseCallBack callBack) {
        LswRequest.getLswScoreResult(doworkId, callBack);
    }

    /**
     * 获取听说模考作业或自主练习评分
     *
     * @param doworkId 提交作业或练习返回的doworkId, 不是workId
     */
    public void getEssayScoreResult(String doworkId, final BaseCallBack callBack) {
        LswRequest.getEssayScoreResult(doworkId, callBack);
    }

}
